import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/**
 * This class performs word counting on a the syystem's standard input
 * @author Mathieu Morel, Pradyut Pokuri, Emily Rice
 * @version 1.0
 */
public class StandardInputWordCounter {

	private int wordCounter = 0;

	public StandardInputWordCounter() {
		super();
	}

	/**
	 * Method that counts and displays on the system's standard output the number of words typed in the system's
	 * standard input 
	 * @param delims the regular expression of all the delimiters
	 * @throws IOException
	 */
	public void wordCount(String delims) throws IOException {
		//Using the Scanner class to tokenize, parse and count input
		Scanner s = null;
		
		//Reading from system standard input
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		try {
			
			//Prompt user to start typing
			System.out.println("Enter your input: ");
			
			String typedText = null;
			typedText = br.readLine();

			s = new Scanner(typedText);
			
			//Use the Scanner class's useDelimiter object to create tokens from input
			//broken up by specified delims
			s.useDelimiter(delims);
			
			while (s.hasNext()) {
				
				if(wordCounter == Integer.MAX_VALUE )
					//If word count equals max size of a Java int, print an error
					throw new Exception("Overflow");
				wordCounter++;
				s.next();
			}
			//Print result
			System.out.println("The result is: " + wordCounter +" words");
		}
		catch (Exception e){
			if (e.getMessage() == "Overflow"){ //Exception if word count equals max int
				System.out.println("ERROR: file contains too many words");	
			}
	
		} finally {
			if (s != null) {
				//Close at the end
				s.close();
				// and exit program
				System.exit(0);
			}
		}
	}
}